#!/bin/bash
# 程序查询脚本
# 作者: 丁文
# 时间: 2025-04-09 22:00:05
# Check if ss or netstat is installed
check_command() {
    if command -v ss >/dev/null 2>&1; then
        echo "ss command is available, using ss."
        return 0
    elif command -v netstat >/dev/null 2>&1; then
        echo "ss not found, using netstat."
        return 1
    else
        echo "Error: Neither ss nor netstat command found."
        echo "Please install one of these tools."
        exit 1
    fi
}

# Function to install missing tools
install_tools() {
    echo "Attempting to install the required tools..."

    if command -v apt-get >/dev/null 2>&1; then
        # Ubuntu/Debian systems
        sudo apt-get update && sudo apt-get install -y iproute2 net-tools
    elif command -v yum >/dev/null 2>&1; then
        # CentOS/RedHat systems
        sudo yum install -y iproute net-tools
    elif command -v dnf >/dev/null 2>&1; then
        # Fedora systems
        sudo dnf install -y iproute net-tools
    elif command -v zypper >/dev/null 2>&1; then
        # openSUSE systems
        sudo zypper install -y iproute2 net-tools
    else
        echo "Unsupported package manager. Please manually install iproute2 and net-tools."
        exit 1
    fi
}

# Process query function
query_process() {
    local query_type=$1
    local query_value=$2

    case $query_type in
        "name")
            echo "Searching for processes with name '$query_value'..."
            ps aux | grep -i "$query_value" | grep -v grep
            ;;
        "pid")
            echo "Searching for process with PID '$query_value'..."
            ps -p "$query_value" -o pid,ppid,cmd,%cpu,%mem
            ;;
        "port")
            echo "Searching for process using port '$query_value'..."
            if check_command; then
                ss -tuln | grep ":$query_value" | awk '{print $6}' | cut -d',' -f2 | while read pid; do ps -p $pid -o pid,ppid,cmd,%cpu,%mem; done
            else
                netstat -tuln | grep ":$query_value" | awk '{print $7}' | cut -d'/' -f1 | while read pid; do ps -p $pid -o pid,ppid,cmd,%cpu,%mem; done
            fi
            ;;
        *)
            echo "Invalid query type. Available query types: name, pid, port"
            exit 1
            ;;
    esac
}

# Main program
echo "Please enter the query type (name, pid, port):"
read query_type
echo "Please enter the query value:"
read query_value

# Call the query function
query_process "$query_type" "$query_value"
